package com.trickytriad.services.remote
{
	import com.adobe.serialization.json.JSON;
	import com.trickytriad.events.game.GetGamesOfPlayerEvent;
	import com.trickytriad.model.GameData;
	import com.trickytriad.model.TileData;
	import com.trickytriad.services.interfaces.I_GameService;
	import com.trickytriad.util.FacebookService;
	
	import flash.events.EventDispatcher;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	/**
	 * Implementation of the service that uses the remote HTTPService.
	 */
	public class GameServiceImpl_Remote extends EventDispatcher implements I_GameService
	{
		// Remote HTTP Service
		public var httpService:HTTPService;
					
		// Callback function
		private var _callback:Function;					
					
		public function GameServiceImpl_Remote()
		{
			httpService = new HTTPService();
			httpService.url = "http://mike.frad.org/tt-0.3/gamerequest.php";
			httpService.resultFormat = "text";
			httpService.useProxy = false;
			httpService.method = "POST";
		}

		/**
		 * Sets the callback function that will be executed when the HTTPService request is done.
		 */
		public function setCallback(callback:Function) : void
		{
			_callback = callback;
		}

		/**
		 * Function that retrieves the games of the player from the PHP server.
		 */
		public function getGamesOfPlayerFromServer(evt:GetGamesOfPlayerEvent):void
		{			
			// Create a new request parameters object
			var sendObj:Object = FacebookService.makeFacebookObject();
			sendObj.GETALLGAMES = "true";
			if (evt._game_id != -1)
			{
				sendObj.game_id = evt._game_id;
			}
			else if (evt._player_id != -1)
			{
				sendObj.player_id = evt._player_id;
			}
			else // Neither player_id nor game_id are valid, error
			{
				getGamesOfPlayerFromServerFault(new FaultEvent(FaultEvent.FAULT));
			}
			httpService.addEventListener(ResultEvent.RESULT, getGamesOfPlayerFromServerResult);
			httpService.addEventListener(FaultEvent.FAULT, getGamesOfPlayerFromServerFault);
			httpService.send(sendObj);
		}
		
		/**
		 * Result handler for a request to get games of the player from the server.
		 */ 
		public function getGamesOfPlayerFromServerResult(evt:ResultEvent) : void
		{			
			// Remove listeners
			httpService.removeEventListener(ResultEvent.RESULT, getGamesOfPlayerFromServerResult);			
			httpService.removeEventListener(FaultEvent.FAULT, getGamesOfPlayerFromServerFault);			
			
			if (String(evt.result).length < 1)
			{			
				return;
			}
			//trace("Got to the getAllGamesRequestResult.  Resulting game_ids:");
		    //trace(String(evt.result));
			var resultObject:Object = JSON.decode(String(evt.result));
			var glArray:Array = new Array();			
			for each(var gameObject:Object in resultObject)
			{
				var tileDataArray:Array = new Array();
				var p1handArray:Array = new Array();
				var p2handArray:Array = new Array();				
				for each (var tileDataObject:Object in gameObject.boardArray)
				{
					// Generate TileData objects from the boardArray property
					// trace(ObjectUtil.toString(tileDataObject));
					tileDataArray.push(new TileData(tileDataObject.card_id, tileDataObject.controller, tileDataObject.element));					
				}
				// Generate player hands
				for each (var hand1DataObject:Object in gameObject.p1cards)
				{					
					p1handArray.push(new TileData(hand1DataObject.card_id, hand1DataObject.controller, 0));									
				}
				for each (var hand2DataObject:Object in gameObject.p2cards)
				{
					p2handArray.push(new TileData(hand2DataObject.card_id, hand2DataObject.controller, 0));									
				}

				
				// Create a new GameData object out of the gameObject
				var gdata:GameData = new GameData(gameObject.game_id, gameObject.player1_id, gameObject.player2_id, tileDataArray, p1handArray, p2handArray,
						gameObject.turn, gameObject.gamestarted, gameObject.winner);
				// Push into array
				glArray.push(gdata);
			}
			var gameDoneEvent:GetGamesOfPlayerEvent = new GetGamesOfPlayerEvent(GetGamesOfPlayerEvent.GETGAMESOFPLAYER_DONE, -1, -1, glArray);
			_callback(gameDoneEvent);	
		}
		
		/**
		 * Fault handler, if there's an error with the HTTPService call.
		 */
		public function getGamesOfPlayerFromServerFault (evt:FaultEvent) : void
		{
			httpService.removeEventListener(ResultEvent.RESULT, getGamesOfPlayerFromServerResult);			
			httpService.removeEventListener(FaultEvent.FAULT, getGamesOfPlayerFromServerFault);		
		}
		
	}
}